package com.dosh;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * The MainActivity is the start page. 
 * Its used to log in and load all needed Informations of the actual User.
 */
public class MainActivity extends Activity implements OnClickListener {

	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	public static User currentUser;
	public static Cycle[] cycles;
	public static long log;
	TextView user,password;
	Button login, register;
	public DBAdapter db = new DBAdapter(this);
	
	/**
	 * 
	 * animates the logo at the beginning
	 */
	private void StartAnimations() {
		Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
		anim.reset();
		RelativeLayout l = (RelativeLayout) findViewById(R.id.linlay);
		l.clearAnimation();
		l.startAnimation(anim);
		anim = AnimationUtils.loadAnimation(this, R.anim.translate);
		anim.reset();
		ImageView iv = (ImageView) findViewById(R.id.logo);
		iv.clearAnimation();
		iv.startAnimation(anim);
		
		
		

	}
	/**
	 * This method loads all Buttons, Textfileds and creates all Cycles.
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * calls the animation
         */
        StartAnimations();
		Thread timer = new Thread() {
			public void run() {
				try {
					sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
				}
			}
		};
		timer.start();
        
      //Connects the variable with its field
        user=(TextView) findViewById(R.id.main_user_field);
        password=(TextView) findViewById(R.id.main_password_field);
        
        login=(Button) findViewById(R.id.main_login_button);
        login.setOnClickListener(this);
        
        register=(Button) findViewById(R.id.main_register_button);
        register.setOnClickListener(this);
        
        //Creates the needed Cycles
        cycles = new Cycle[10];
        cycles[0] = new Cycle(0, this.getString(R.string.cycle_day), 0);
        cycles[1] = new Cycle(1, this.getString(R.string.cycle_day), 1);
        cycles[2] = new Cycle(2, this.getString(R.string.cycle_day), 2);
        cycles[3] = new Cycle(1, this.getString(R.string.cycle_week), 3);
        cycles[4] = new Cycle(2, this.getString(R.string.cycle_week), 4);
        cycles[5] = new Cycle(1, this.getString(R.string.cycle_month), 5);
        cycles[6] = new Cycle(2, this.getString(R.string.cycle_month), 6);
        cycles[7] = new Cycle(3, this.getString(R.string.cycle_month), 7);
        cycles[8] = new Cycle(6, this.getString(R.string.cycle_month), 8);
        cycles[9] = new Cycle(1, this.getString(R.string.cycle_year), 9);
  
    }
    /**
	 * This method checks, if there are Jobs in the past and executes them.
	 */
    public static void checkJob(DBAdapter db){
    	//loads all unfinished jons
    	db.open();
    	Cursor c = db.rawQuery("SELECT Job.Job_ID, Job.Expiring, Job.Amount, Budget.Name " +
    							"FROM Job " +
    							"LEFT JOIN Planning on Planning.Planning_ID = Job.Planning "+
    							"LEFT JOIN Budget on Budget.Budget_ID = Planning.Budget "+
    							"WHERE Budget.User_ID="+currentUser.user_ID+";");	
    	db.close();
    	if(c!=null){
    		//loads the actual Date
    		GregorianCalendar cal = new GregorianCalendar(); 
	    	Date today = cal.getTime();
	    	today.setMonth(today.getMonth()+1);
	    	today.setYear(cal.get(Calendar.YEAR));
	    	today.setHours(0);
	    	today.setMinutes(0);
	    	today.setSeconds(0);
	    	String[] helpdat = new String[3];
	    	Date dat;
	     	do{
	     		//creates a Date data for the current Job
	        	helpdat=c.getString(1).split("\\.",3);
	        	dat = new Date(Integer.parseInt(helpdat[2]),Integer.parseInt(helpdat[1]),Integer.parseInt(helpdat[0]));
	        	
	        	//If the job is in the past, it gets executed
	        	if(dat.compareTo(today) <= 0){
	        		System.out.println(c.getString(0)+" "+c.getString(1)+" "+c.getString(2)+" "+c.getString(3)+" "+dat.getDate()+"."+dat.getMonth()+"."+dat.getYear()+" "+dat.compareTo(today));
	        		Job j = new Job(c.getLong(0), db);
	        		Budget bud = currentUser.createBuget(c.getString(3), 0, "", "", db);
	        		j.jobDone(db, bud);
	        	}
	    	}while(c.moveToNext());
    	}
    }
    /**
	 * This method sets the OnClickListener.
	 * The Login-Button checks the insertion an logs in the User. 
	 * The Register-Button leads to the Register activity.
	 */
	public void onClick(View view) {
		// TODO Auto-generated method stub
		String users = user.getText().toString();
		String passwords = password.getText().toString();
		db.open();

		if(view==login){
			//checks the login input
			db.open();
			MainActivity.log = db.check_login(users, passwords);
			db.close();
			if(MainActivity.log>-1){
				//Starts the Homepage Activity and sets the Current User
				Intent in= new Intent(MainActivity.this, Homepage.class);
				in.putExtra("username", users);
				startActivity(in);
				MainActivity.currentUser = new User(MainActivity.log, db);
				checkJob(db);
			}else{
				//deletes the fields, if the input was wrong
				user.setText(null);
				password.setText(null);
				Toast.makeText(MainActivity.this,"Anmeldedaten Falsch!", Toast.LENGTH_LONG).show();
			
			}
			
		}

		//leads to the register Activity
		else if(view==register){
			Intent in= new Intent(MainActivity.this, Register.class);	
			startActivity(in);
		}
		
	}
   
}
